package com.cipe.cmrs.controllers;

import javax.servlet.http.HttpServletRequest;


import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.cipe.cmrs.bean.DonorAwardBean;
import com.cipe.cmrs.converter.DateEditor;
import com.cipe.cmrs.model.Donoraward;
import com.cipe.cmrs.model.User;
import com.cipe.cmrs.service.CountryService;
import com.cipe.cmrs.service.DonorService;
import com.cipe.cmrs.service.DonorawardService;
import com.cipe.cmrs.service.DonorawardstatusService;
import com.cipe.cmrs.service.DonorawardtypeService;
import com.cipe.cmrs.util.Constants;
import com.cipe.cmrs.util.DateUtil;
import com.cipe.cmrs.util.DateUtil2;
import com.cipe.cmrs.util.UserUtil;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;


@Controller
public class DonorawardController extends BaseController {

	private static final long				serialVersionUID	= 1815579886981166259L;
	@Autowired
	private DonorawardService				donorawardService;
	@Autowired
	private DonorService					donorService;
	@Autowired
	private DonorawardtypeService			donorawardtypeService;
	@Autowired
	private CountryService					countryService;
	@Autowired
	private DonorawardstatusService			donorawardstatusService;
	
	@InitBinder
	public void initBinder(WebDataBinder binder) {
		super.initBinder(binder);
		binder.registerCustomEditor(java.util.Date.class, new DateEditor(Constants.DefaultDateFormat, Constants.DefaultDateFormat));
	}
	
    @RequestMapping("/secure/findDonoraward.do")
    public String findDonoraward(@ModelAttribute("donoraward") Donoraward donoraward,
        @RequestParam(value = "initiateSearch", required = false) String initiateSearch, Model model) {
        model.addAttribute("donoraward", new Donoraward());
        model.addAttribute("donorList", donorService.findAllOrderBy("donorName"));
        model.addAttribute("donorawardstatusList", donorawardstatusService.findAllOrderBy("displayName"));
        if (StringUtils.isNotBlank(initiateSearch)) {
            model.addAttribute("donorawardList", donorawardService.findDonoraward(donoraward));
            model.addAttribute("donoraward", donoraward);
            model.addAttribute("initiateSearch", initiateSearch);
        }
        return "findDonoraward";
    }

    @RequestMapping("/secure/findsearchDonoraward.do")
    public String findsearchDonoraward(@ModelAttribute("donoraward") Donoraward donoraward,
        @RequestParam(value = "initiateSearch", required = false) String initiateSearch, Model model) {
        model.addAttribute("donoraward", new Donoraward());
        model.addAttribute("donorList", donorService.findAllOrderBy("donorName"));
        model.addAttribute("donorawardstatusList", donorawardstatusService.findAllOrderBy("displayName"));
        model.addAttribute("donorawardList", donorawardService.findDonoraward(donoraward));
      /*  if (StringUtils.isNotBlank(initiateSearch)) {
            model.addAttribute("donorawardList", donorawardService.findDonoraward(donoraward));
            model.addAttribute("donoraward", donoraward);
            model.addAttribute("initiateSearch", initiateSearch);
        }*/
        return "searchResultfindDonoraward";
    }

    
	@RequestMapping("/secure/findResultDonorawardWithProcedure.do")
	public String findResultDonorawardWithProcedure(@ModelAttribute("donoraward") Donoraward donoraward, Model model) {
		model.addAttribute("donoraward", donoraward);
		model.addAttribute("donorList", donorService.getAllDonors());
		model.addAttribute("donorawardList", donorawardService.findDonoraward(donoraward.getPrc()));
		model.addAttribute("message",donoraward.getMessage());
		model.addAttribute("initiateSearch", "initiateSearch");
		return "findDonorawardDashboard";
	}

	@RequestMapping(value = "/secure/getDonorAwardBean.do", method = RequestMethod.GET)
    public @ResponseBody
    DonorAwardBean getDonorAward(@RequestParam("donorawardId") Integer donorAwardId) {
        if (donorAwardId != null && donorAwardId > 0) {
            return donorawardService.getDonorAward(donorAwardId);
        } else {
            return null;
        }
    }

	@RequestMapping("/secure/saveDonoraward.do")
	public String SaveDonoraward(@ModelAttribute("donoraward") Donoraward donoraward, BindingResult result, Model model, HttpServletRequest request) {
		String page = "editDonoraward";
		try {
			donoraward = donorawardService.saveDonoraward(donoraward, getUserId(request));
			updatePrevValues(donoraward);
			saveMessage(request, getText("editDonoraward.message.success"));

			String action = request.getParameter("action");
			String saveAndViewDonorAction = getText("editDonoraward.button.saveandviewdonor");
			if (saveAndViewDonorAction.toLowerCase().equals(action.toLowerCase())) {
				return "redirect:showEditDonor.do?id=" + donoraward.getDonor().getId();
			}
		} catch (javax.persistence.PersistenceException nuEx){
			logger.error(getText("editDonoraward.message.duplicateNumber"), nuEx);
			saveError(request, getText("editDonoraward.message.duplicateNumber"));		
		}
		
		catch (Exception e) {
			logger.error(getText("error.transaction"), e);
			saveError(request, getText("error.transaction"));
		}
		model.addAttribute("donoraward", donoraward);
		model.addAttribute("donorList", donorService.getAllDonors());
		model.addAttribute("countryList", countryService.findAll());
		model.addAttribute("donorawardtypeList", donorawardtypeService.findAll());
		model.addAttribute("donorawardstatusList", donorawardstatusService.findAll());
		model.addAttribute("mode", request.getParameter("mode"));
		return page;
	}

	@RequestMapping("/secure/showAddDonoraward.do")
	public String showAddDonoraward(Model model, HttpServletRequest request) {
		Donoraward donoraward = new Donoraward();
		donoraward.setAttachmentName("S:\\Scanned Documents\\Donor Awards\\" );		
		User user = UserUtil.INSTANCE.getCurrentUser();
		donoraward.setCreatedBy(user);
		donoraward.setCreationDate(DateUtil.getCurrentDate());
		donoraward.setUpdatedBy(user);
		donoraward.setUpdationDate(DateUtil.getCurrentDate());		
		model.addAttribute("donoraward", donoraward);
		model.addAttribute("donorList", donorService.getAllDonors());
		model.addAttribute("countryList", countryService.findAll());
		model.addAttribute("donorawardtypeList", donorawardtypeService.findAll());
		model.addAttribute("donorawardstatusList", donorawardstatusService.findAll());
		return "editDonoraward";
	}

	@RequestMapping("/secure/showDonorawardList.do")
	public String showDonorawardList(Model model) {
		model.addAttribute("donorawardList", donorawardService.findAll());
		return "donorawardList";
	}

	@RequestMapping("/secure/showEditDonoraward.do")
	public String showEditDonoraward(@RequestParam Integer id, Model model) {
	    Donoraward donorAward = donorawardService.findById(id);
	    updatePrevValues(donorAward);
		model.addAttribute("donoraward", donorAward);
		model.addAttribute("donorList", donorService.getAllDonors());
		model.addAttribute("countryList", countryService.findAll());
		model.addAttribute("donorawardtypeList", donorawardtypeService.findAll());
		model.addAttribute("donorawardstatusList", donorawardstatusService.findAll());
		model.addAttribute("mode", "editMode");
		return "editDonoraward";
	}
	
	@RequestMapping(value="/secure/showDonorawardByDonor.do", method=RequestMethod.GET)
	public @ResponseBody Map<String,String> showDonorawardByDonor(@RequestParam Integer id, Model model) {
		Map<String,String> results=new LinkedHashMap<String, String>();
	    List<Donoraward> donorAwardList = donorawardService.getDonorawardByDonorawardNumberOrByDonor("",id);
	    if(donorAwardList!=null)
	    {
	       for(Donoraward tempDonorAward:donorAwardList)
	       {
	    	   results.put(tempDonorAward.getFullDonorawardNumber(),tempDonorAward.getId().toString());
	       }
	    	
	    }
    
		return results;
	}
	
    private void updatePrevValues(Donoraward donorAward) {
        donorAward.setPrevStartDate(DateUtil2.INSTANCE.formatDate(donorAward.getStartDate()));
        donorAward.setPrevEndDate(DateUtil2.INSTANCE.formatDate(donorAward.getEndDate()));
        if (donorAward.getDirectFunds() != null) {
            donorAward.setPrevDirectFunds(donorAward.getDirectFunds());
        }
        if (donorAward.getIndirectFunds() != null) {
            donorAward.setPrevIndirectFunds(donorAward.getIndirectFunds());
        }
        if (donorAward.getDonorawardstatus() != null) {
            donorAward.setPrevStatusId(donorAward.getDonorawardstatus().getId());
        }
    }
}
